;(function (factory, root) {

    if (!window.SocketServer) {
        window.SocketServer = factory();
    }

})(function () {
   
    var SocketServer = function (user) {
        this.user = user;
        this.callbacks = [];
        this.init();
    };

    SocketServer.prototype = {
        init: function () {
            this.socketUrl = "wss://localhost:443/exercise_server/" + this.user;
            this.socket = new WebSocket(this.socketUrl);
            var that = this;
            this.socket.onmessage = function (message) {
                that.callbacks.forEach(element => {
                    element(message.data);
                });
            };
            var websocket = this.socket;
            window.onbeforeunload = function(){ 
              websocket.onclose = function(){};
              websocket.close();
            }; 
        },
        onMessage: function (call) {
            this.callbacks.push(call);
        }
    };


    return SocketServer;
}, this);